import axios, { AxiosInstance, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from 'axios';
import errorCode from './errorCode'
import { useMessage } from '@renderer/hooks/message'
import { useMd5 } from '@renderer/hooks/md5'
const md5Hook = useMd5()
const messageTip = useMessage()

const generateSignature = (url: string, t: number, key: string) => {
    // 构建签名字符串
    const signStr = `url=${url}||t=${t}||key=${key}`
    // 使用 MD5 加密
    const md5Hash = md5Hook.hashStr(signStr).toUpperCase()
    const signature = md5Hook.hashStr(md5Hash.substring(8, 16)).toUpperCase()

    return signature
}

const baseURL = import.meta.env.MODE === 'production' ? 'http://test-pucs.riding-evolved.com' : '/api'
const instance: AxiosInstance = axios.create({
    baseURL,
    // 超时
    timeout: 1000 * 5
})

// 添加请求拦截器
instance.interceptors.request.use((config: any) => {
    const { url = "", isSign = true } = config;

    if (isSign) {
        const t = Math.floor(+new Date() / 1000)
        const key = 'opeddsaeaddadbcabf'
        const id = 'c4d89e9ed4f9d1c8d3e8bcee0684f076'
        const sign = generateSignature(url, t, key)

        config.headers = {
            t,
            sign,
            id
        }
    }
    
    return config
}, (error: any) => {
    // 处理请求错误
    return Promise.reject(error);
})

// 添加响应拦截器
instance.interceptors.response.use((response: AxiosResponse) => {
    let { code, msg } = response.data;
    // 未设置状态码则默认成功状态
    code = code || 200;
    msg = errorCode[code] || msg || errorCode["default"];

    if (code !== 200) {
        messageTip.error(msg)
        return Promise.reject(code);
    } else {
        return response;
    }
}, (error: any) => {
    // 处理响应错误
    return Promise.reject(error);
})


export default instance;